package com.v8dn.app.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.v8dn.app.bean.AuthorityBean;
import com.v8dn.app.bean.RoleBean;
import com.v8dn.app.bean.UserBean;
import com.v8dn.app.mapper.UserMapper;

@Service("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService{

	private static Log log=LogFactory.getLog(UserDetailServiceImpl.class);

	@Autowired
	@Qualifier("mapper.userMapper")
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
		log.info("用户名:"+username);
		if(username==null){
			log.error("username is null");
		}
		if(userMapper==null){
			log.error("userMapper is null");
		}
		UserBean user=this.userMapper.getUserByName(username);
		if(user==null){
			log.error(username+" is not exist",new UsernameNotFoundException(username+" is not exist"));
		}
		log.info("Password:"+user.getUserPassword());
		User userdetail=new User(user.getUserAccount(),user.getUserPassword(),true,true,true,true,getAuthorities(user));
		return userdetail;
	}

	/**
	 * @title 获得访问角色权限
	 * @param access
	 * @return
	 */
	public Collection<GrantedAuthority> getAuthorities(UserBean user){
		List<GrantedAuthority> authsList=new ArrayList<GrantedAuthority>();
		for(RoleBean roleBean:user.getRole()){
			for(AuthorityBean authorityBean:roleBean.getAuthorityBean()){
				authsList.add(new SimpleGrantedAuthority(authorityBean.getAuthName()));
			}
		}
		log.info("authsList:"+authsList);
		return authsList;
	}

}